<template>
	<view class="ve-upload">
		<view class="ve-upload-item" v-for="(item,index) in imgList" :key="index">
			<image class="banner" :src="item.img" @tap="preview(index)" mode="aspectFill"></image>
			<view v-if="!disabled" class="delete-icon" @click="deleteItem(index)">
				<ve-icon name='delete' width="36"></ve-icon>
			</view>
		</view>
		<view class="upload flex-column-center" @click="uploadItem()" v-if="!disabled && (count==0 || count>imgList.length)">
			<ve-icon name='plus' width="52"></ve-icon>
		</view>
	</view>
</template>

<script>
	
	// 此组件为除短租订单外的使用
	
	
	// #ifdef APP-PLUS
	import permision from "@/common/permission.js"
	// #endif
	export default {
		props: {
			// 个数  0不限制或20以内
			count: {
				type: String | Number,
				default: 9
			},
			// 初始列表，对象item.img必传
			list: {
				type: Array,
				default: () => {
					return []
				}
			},
			disabled: Boolean
		},
		data() {
			return {
				imgList: this.list, // 照片列表
				sdk: undefined,
				pageDisabled: false,
				successNum: 0, //本次上传成功个数
			}
		},
		mounted() {
			var _this=this;
			setTimeout(function() {
				// console.log(_this.list)
				if(_this.list.length){
					_this.getPicture(_this.list)
				}
			},300);
		},
		methods: {
			uploadItem() {
				if(this.pageDisabled==true){return false}
				this.pageDisabled = true;
				// #ifdef APP-PLUS
				permision.requestAndroidPermission("android.permission.CAMERA").then(res => {
					if (res == 1) {
						permision.requestAndroidPermission("android.permission.READ_EXTERNAL_STORAGE").then(
							res => {
								if (res == 1) {
									// #endif
									const _this = this;
									_this.sdk = undefined;
									_this.compareVersion();
									if(!_this.sdk){return false}
									// 基础库限制
									if (_this.sdk == 1) {
										var uploadCount;
										uploadCount = _this.count==0?20:(_this.count-_this.imgList.length);
										uni.getSystemInfo({
											success(res) {
												if(res.brand =='devtools'){
													console.log('模拟器调试最多仅支持9张，已更改为9')
													uploadCount = 9;
												}
											}
										})
										uni.chooseMedia({
											count: uploadCount>20?20:uploadCount,
											mediaType: ['image'],
											sourceType: ['album', 'camera'],
											sizeType: ['original', 'compressed'],
											camera: 'back',
											success(res) {
												_this.uploadServe(res.tempFiles.sort( function(a,b){return b-a} ));
											},
											complete: (r) => {
												if(r.errMsg == 'chooseMedia:fail cancel'){
													_this.pageDisabled = false;
												}
											}
										})
									} else {
										var uploadCount = _this.count==0?9:(_this.count-_this.imgList.length);
										uni.chooseImage({
											count: uploadCount>9?9:uploadCount,
											sizeType: ['compressed'],
											sourceType: ['album', 'camera'],
											success(res) {
												_this.uploadServe(res.tempFilePaths.sort( function(a,b){return b-a} ));
											},
											complete: (r) => {
												if(r.errMsg == 'chooseImage:fail cancel'){
													_this.pageDisabled = false;
												}
											}
										})
									}
									// #ifdef APP-PLUS
								}
							})
					}
				})
				// #endif
			},
			// 上传服务器
			uploadServe(fs){
				uni.showLoading({
					title: '正在上传'
				})
				var _this = this;
				this.pageDisabled = true;
				var fsLength = fs.length;
				fs.forEach((i, index)=>{
					// 启用压缩
					uni.compressImage({
						src: i.tempFilePath,
						quality: 80,
						success: res => {
							var imgPath = res.tempFilePath;
							uni.uploadFile({
								url: getApp().globalData.requestUrl + "/uploadFile/commonUpload",
								filePath: imgPath,
								name: 'files',
								header: {
									'content-type': 'multipart/form-data',
									'service-code': 'H5',
									"ticket": uni.getStorageSync('userInfo').token
								},
								success: (res) => {
									res.data = JSON.parse(res.data)
									if (res.data.code == 200) {
										_this.successNum = _this.successNum+1
										// console.log(_this.successNum)
										_this.uploadSuccess(res.data.result[0], fsLength)
									} else {
										uni.showToast({
											title: res.data.message ? res.data.message :'网络异常,请稍后再试',
											icon: 'none'
										})
									}
								},
								fail: (err) => {
									uni.showToast({
										title: '网络异常,请稍后再试',
										icon: 'none'
									})
									_this.pageDisabled = false;
								},
								complete: () => {
									uni.removeSavedFile({
										filePath: imgPath
									})
								}
							})
						}
					})
				})
			},
			// 上传成功
			uploadSuccess(data, fsLength) {
				var _this = this;
				uni.showLoading({
					title: _this.successNum + '/' + fsLength + '张'
				})
				// console.log(data)
				// console.log(_this.successNum)
				this.$forceUpdate()
				const imgObj = {
					img: data.openUrl,
					fileId: data.fileIdStr
				}
				_this.imgList.push(imgObj)
				_this.emitChange(_this.imgList.length - 1);
				if(_this.successNum == fsLength){
					uni.hideLoading()
					uni.showToast({
						title: '上传完毕',
						icon: 'none'
					})
					_this.pageDisabled = false;
					_this.successNum = 0;
					return
				}
				// else{
				// 	setTimeout(function() {
				// 		uni.hideLoading()
				// 		uni.showToast({
				// 			title: '请检查是否有遗漏图片',
				// 			icon: 'none'
				// 		})
				// 		_this.pageDisabled = false;
				// 		_this.successNum = 0;
				// 	},30000);
				// }
			},
			// 删除一个
			deleteItem(index) {
				if(this.pageDisabled==true){return false}
				this.imgList.splice(index, 1);
				this.emitChange(index);
			},
			// 提交change
			emitChange(index) {
				this.$emit('change', this.imgList, index);
			},
			// 照片预览
			preview(index) {
				if(this.pageDisabled==true){return false}
				uni.previewImage({
					urls: this.imgList.map(item => item.img),
					current: index
				})
			},
			// 微信基础库版本判断   compareVersion('1.11.0', '2.11.1') // 1
			compareVersion() {
				var _this = this;
				var v1 = '';
				var v2 = '2.25.0';
				uni.getSystemInfo({
					success(res) {
						if(res.SDKVersion){
							v1 = res.SDKVersion.split('.')
							v2 = v2.split('.')
							const len = Math.max(v1.length, v2.length)
							while (v1.length < len) {
								v1.push('0')
							}
							while (v2.length < len) {
								v2.push('0')
							}
							for (let i = 0; i < len; i++) {
								const num1 = parseInt(v1[i])
								const num2 = parseInt(v2[i])
								if (num1 > num2) {
									_this.sdk = '1'
									return
								} else if (num1 < num2) {
									_this.sdk = '-1'
									return
								}
							}
							_this.sdk = '-0'
							return
						}
					}
				})
			},
			// 获取照片
			getPicture(list) {
			  this.request('/uploadFile/getFileInfoList', {
			    idList: list.map((item) => item.fileIdStr || item.fileId || item),
			  })
			    .then((res) => {
					console.log(res)
			      if (res.code == 200 && res.result.length) {
			        this.imgList = res.result.map((item, index) => {
			          return {
			            img: item.openUrl,
			            fileId: item.fileIdStr,
			          }
			        })
					this.$forceUpdate()
			        // this.handleUpload()
					this.emitChange(this.imgList.length - 1);
			      }
			    })
			    .catch((_) => {})
			},
			/**
			 * 更新数据
			 */
			handleUpload() {
				const newValue = this.imgList.map((item) => item.fileId)
				// this.$emit('input', newValue)
				this.$emit('change', newValue)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.ve-upload {
		padding-top: 10rpx;
		display: flex;
		flex-wrap: wrap;

		&-item {
			position: relative;
			width: 170rpx;
			height: 170rpx;
			margin-bottom: 32rpx;
			margin-right: 32rpx;
			box-sizing: border-box;

			.banner {
				width: 180rpx;
				height: 180rpx;
				border-radius: 8rpx;
				border: 2rpx solid #E2E2E2;
			}

			.banner:nth-child(3n) {
				margin-right: 0 !important;
			}

			.delete-icon {
				width: 36rpx;
				height: 36rpx;
				position: absolute;
				top: -16rpx;
				right: -16rpx;
				z-index: 1;
			}
		}

		.upload {
			width: 180rpx;
			height: 180rpx;
			border-radius: 8rpx;
			border: 2rpx dashed #E2E2E2;
		}
	}
</style>
